package com.chuantou.yuba.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;

public class StackManager {

	/**
	 * activity计数器
	 */
	public static final Map<String, List<Activity>> COUNTER = new HashMap<String, List<Activity>>();

	private static Activity sCurrentActivity = null;

	/**
	 * activity创建时调用此方法
	 * 
	 * @param activity
	 */
	public static void onActivityCreated(Activity activity) {
		String activityName = activity.getClass().getName();
		List<Activity> acitivies = COUNTER.get(activityName);
		if (acitivies == null) {
			acitivies = new ArrayList<Activity>();
			COUNTER.put(activityName, acitivies);
		}
		acitivies.add(activity);
	}

	/**
	 * activity销毁时调用此方法
	 * 
	 * @param activity
	 */
	public static void onActivityDestroied(Activity activity) {
		String activityName = activity.getClass().getName();
		List<Activity> acitivies = COUNTER.get(activityName);
		if (acitivies != null) {
			acitivies.remove(activity);
		}
		// 同一实例，
		if (activity == sCurrentActivity) {
			setCurrentActivity(null);
		}
	}

	/**
	 * 设置当前Activity
	 * 
	 * @param activity
	 */
	public static void setCurrentActivity(Activity activity) {
		sCurrentActivity = activity;
	}

	/**
	 * 获取当前显示的Activity
	 * 
	 * @return
	 */
	public static Activity getCurrentActivity() {
		return sCurrentActivity;
	}

	/**
	 * 清除所有的activity
	 */
	public static final void finishAll() {
		for (String key : COUNTER.keySet()) {
			finishActivty(key);
		}
		COUNTER.clear();
	}

	/**
	 * 清除指定的activity
	 * 
	 * @param activityName
	 */
	public static final void finishActivty(String activityName) {
		List<Activity> activities = COUNTER.get(activityName);
		if (activities != null && !activities.isEmpty()) {
			for (Activity activity : activities) {
				if (activity != null) {
					activity.finish();
				}
			}
			activities.clear();
		}
	}

	public static final boolean hasActivityInStack(String activityName) {
		List<Activity> activities = COUNTER.get(activityName);
		return activities != null && !activities.isEmpty();
	}
}
